package com.tang.qzzp.config;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tang.qzzp.entity.User;
import com.tang.qzzp.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.servlet.OncePerRequestFilter;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @Author 唐海清
 * @Version V1.0
 * @Description 防止Session丢失
 */
@Slf4j(topic = "AddPrincipalToSessionFilter")
public class AddPrincipalToSessionFilter extends OncePerRequestFilter {
    @Resource
    private UserService userService;

    @Override
    protected void doFilterInternal(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws ServletException, IOException {
        Subject subject = SecurityUtils.getSubject();
        //判断用户是不是通过自动登录进来的
        if (subject.isRemembered()) {
            User user = (User) subject.getPrincipal();
            String username = user.getUserName();
            log.info("username : {}", username);
            if (username.isEmpty()) {
                return;
            }
            QueryWrapper<User> wrapper = new QueryWrapper<>();
            wrapper.eq("user_name", username);
            User currentUser = userService.getOne(wrapper);
            if (currentUser == null) {
                return;
            }
            //这里发现可以将servletRequest强转为子类，所以使用request.getSession())
            HttpServletRequest request = (HttpServletRequest) servletRequest;
            HttpSession session = request.getSession();
            //当session为空的时候
            if (session.getAttribute("user") == null) {
                //把查询到的用户信息设置为session，时效为3600秒
                session.setAttribute("user", user);
                session.setMaxInactiveInterval(3600);
            }
        }
        filterChain.doFilter(servletRequest, servletResponse);
    }
}
